package xrpc

import (
	ctls "crypto/tls"
	"crypto/x509"
	"errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"os"
)

func NewClient(tls *Tls, addr string, opts ...grpc.DialOption) (conn *grpc.ClientConn, err error) {
	if tls != nil {
		certificate, err := ctls.LoadX509KeyPair(tls.Crt, tls.Key)
		if err != nil {
			return nil, err
		}

		certPool := x509.NewCertPool()
		ca, err := os.ReadFile(tls.CACrt)
		if err != nil {
			return nil, err
		}

		if ok := certPool.AppendCertsFromPEM(ca); !ok {
			return nil, errors.New("AppendCertsFromPEM is false")
		}

		creds := credentials.NewTLS(&ctls.Config{
			Certificates:       []ctls.Certificate{certificate},
			RootCAs:            certPool,
			InsecureSkipVerify: true,
		})

		opts = append(opts, grpc.WithTransportCredentials(creds))
	}

	return grpc.Dial(addr, opts...)
}
